package com.maixin.code.dao;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;

import com.maixin.code.entity.Authority;
import com.maixin.code.entity.Users;


public class UsersDAO  extends BaseDAO<Users>{
	/**
	 * 
	 * @param roleId
	 * @return
	 */
	public List<Users> findUsersByDept(String roleId,Integer start,Integer limit){
		try {
			String hql = " select u.id id ,u.username username,u.loginname loginname,u.email email,u.phone phone,u.createtime createtime, " +
					" u.status status ,u.deptid deptid, r.rolename rolename ,d.deptname deptname "+
					" from users u"+
					" inner join userRole ur on u.id = ur.usersid"+
					" inner join role r on ur.roleid = r.id"+
					" inner join dept d on u.deptid = d.id"+
					" where r.id = :roleId ";
			SQLQuery query =  (SQLQuery) super.getSession().createSQLQuery(hql).
					setFirstResult(start).setMaxResults(limit).setResultTransformer(Transformers.aliasToBean(Users.class));
			query.addScalar("id", Hibernate.INTEGER);
			query.addScalar("username", Hibernate.STRING);
			query.addScalar("loginname", Hibernate.STRING);
			query.addScalar("email", Hibernate.STRING);
			query.addScalar("phone", Hibernate.STRING);
			query.addScalar("createtime", Hibernate.DATE);
			query.addScalar("status", Hibernate.INTEGER);
			query.addScalar("deptid", Hibernate.INTEGER);
			query.addScalar("rolename", Hibernate.STRING);
			query.addScalar("deptname", Hibernate.STRING);
			query.setString("roleId", roleId);
			return query.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据用户ID获得用户的角色和用户对象
	 * @param userid 用户ID
	 * @return
	 */
	public List<Users> findUsersByuser(Integer userid){
		try {
			String sql = "from Users s , Userrole ur,Role r where s.id= ur.usersid and r.id = ur.roleid and s.id = :id";
			Query query = super.getSession().createQuery(sql);
			List list = query.list();
			if(null !=list && list.size()>0){
				return list;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	
	public List<Authority> findAuthorityListByRoleId(Integer roleId){
		try {
			String sql = "from Authority a ,roleAuthority ra ";
			//super.getSession().createCriteria(arg0);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
}
